<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    BFC及其应用 |  Yolin
  </title>
  <meta name="generator" content="hexo-theme-yilia-plus">
  
  <link rel="shortcut icon" href="/favicon.png" />
  
  
<link rel="stylesheet" href="/css/style.css">

  
<script src="/js/pace.min.js"></script>


  

  

<link rel="alternate" href="/atom.xml" title="Yolin" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    <main class="content">
      <section class="outer">
  <article id="post-BFC及其应用" class="article article-type-post" itemscope
  itemprop="blogPost" data-scroll-reveal>

  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  BFC及其应用
</h1>
  

    </header>
    

    
    <div class="article-meta">
      <a href="/2020/02/19/BFC%E5%8F%8A%E5%85%B6%E5%BA%94%E7%94%A8/" class="article-date">
  <time datetime="2020-02-19T12:30:02.000Z" itemprop="datePublished">2020-02-19</time>
</a>
      
  <div class="article-category">
    <a class="article-category-link" href="/categories/CSS/">CSS</a>
  </div>

      
      
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">972字</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">3分钟</span>
        </span>
    </span>
</div>

      
    </div>
    

    
    
    <div class="tocbot"></div>





    

    <div class="article-entry" itemprop="articleBody">
      


      

      
      <h4 id="什么？你只知道KFC？"><a href="#什么？你只知道KFC？" class="headerlink" title="什么？你只知道KFC？"></a>什么？你只知道KFC？</h4><p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/web_img/191.jpeg" alt=""></p>
<p>也罢也罢，今天要说的BFC其实你经常使用，只是面试官问你时却欲言又止，今天我们一起来研究一下</p>
<h2 id="定位方案"><a href="#定位方案" class="headerlink" title="定位方案"></a>定位方案</h2><p>在讲解BFC之前先了解一下常见的定位方案，定位方案是控制元素的布局，有几种常见的方案：</p>
<a id="more"></a>
<h5 id="1、普通流（static）"><a href="#1、普通流（static）" class="headerlink" title="1、普通流（static）"></a>1、普通流（static）</h5><p> 在普通流中，元素按照其在HTML中的先后位置至上而下布局，行内元素水平排列，直到当行被占满然后换行，块级元素则会被渲染为完整的一个新行，除非另外指定，否则所有元素默认都是普通流定位，也可以说普通流中元素位置由改元素在HTML文档中的位置决定.</p>
<h5 id="2、浮动（float）"><a href="#2、浮动（float）" class="headerlink" title="2、浮动（float）"></a>2、浮动（float）</h5><p>在浮动布局中，元素首先按照普通流的位置出现，然后根据浮动的方向尽可能的向左边或右边偏移</p>
<h5 id="3、绝对定位（absolute）"><a href="#3、绝对定位（absolute）" class="headerlink" title="3、绝对定位（absolute）"></a>3、绝对定位（absolute）</h5><p>在绝对定位布局中，元素会整体脱离普通流，因此绝对定位元素不会对其兄弟元素造成影响，而具体元素位置由坐标决定</p>
<h5 id="4，相对定位-relative"><a href="#4，相对定位-relative" class="headerlink" title="4，相对定位(relative)"></a>4，相对定位(relative)</h5><p>在static的基础上，如果我想让一个元素在它本来的位置做一些调整(位移)，我们可以将该元素定位设置为relative，同时指定相对位移(利用top,bottom,left,right)。<br>有一点需要注意的是，相对定位的元素仍然在文档流中，仍然占据着它本来占据的位置空间——虽然它现在已经不在本来的位置了。</p>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/web_img/192.png?x-oss-process=image/resize,m_fill,h_180,w_150" alt=""></p>
<h2 id="BFC"><a href="#BFC" class="headerlink" title="BFC"></a>BFC</h2><p>++Block Formatting Context++（<strong>块级格式上下文</strong>），属于上述定位方案的<strong>普通流</strong>，是页面盒模型布局中的一种css渲染模式，相当于一个独立的容器，里面的元素和外部的元素互相不影响。它是页面中的一块渲染区域，并且有一套渲染规则，它决定了其子元素将如何定位，以及和其他元素的关系和相互作用。</p>
<p>可以把BFC理解为一个封闭的大箱子，箱子内部的元素无论如何翻箱倒海，都不会影响到外部</p>
<h2 id="触发BFC的方式有："><a href="#触发BFC的方式有：" class="headerlink" title="触发BFC的方式有："></a>触发BFC的方式有：</h2><p><strong>1、body根元素</strong></p>
<p><strong>2、浮动元素：float除none以外的值</strong></p>
<p><strong>3、绝对定位元素：position（absolute、fixed）</strong></p>
<p><strong>4、overflow除了visiable以外的值（hidden、auto、scroll）</strong></p>
<p><strong>5、display为表格布局或者弹性布局（inline-block、table-cells、flex）</strong></p>
<h2 id="BFC主要的作用是："><a href="#BFC主要的作用是：" class="headerlink" title="BFC主要的作用是："></a>BFC主要的作用是：</h2><p><strong>1、防止同一BFC容器中的相邻元素间的外边距重叠问题</strong></p>
<p><strong>2、清除浮动</strong>     </p>
<p><strong>3、阻止元素被浮动元素覆盖</strong></p>
<h2 id="BFC特性及应用"><a href="#BFC特性及应用" class="headerlink" title="BFC特性及应用"></a>BFC特性及应用</h2><h4 id="1、同一个BFC下外边距会发生折叠"><a href="#1、同一个BFC下外边距会发生折叠" class="headerlink" title="1、同一个BFC下外边距会发生折叠"></a><strong>1、同一个BFC下外边距会发生折叠</strong></h4><p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/web_img/193.png" alt=""><br>因为两个div元素都处于同一个BFC容器下（这里指body元素）所以第一个div的下边距和第二个div上边距发生了重叠，所以两个盒子之间的距离只有100px，而不是200px</p>
<p>如果想避免外边距的重叠，可以将其放在不同的BFC容器中<br><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/web_img/194.png" alt=""><br>这样两个div之间的距离就是200px了</p>
<h4 id="2、BFC可以包含浮动的元素（清除浮动）"><a href="#2、BFC可以包含浮动的元素（清除浮动）" class="headerlink" title="2、BFC可以包含浮动的元素（清除浮动）"></a><strong>2、BFC可以包含浮动的元素（清除浮动）</strong></h4><p>由于容器内元素浮动，脱离了普通流<br><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/web_img/195.png" alt=""><br>等等，我是管不住你了？</p>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/web_img/196.jpg" alt=""></p>
<p>如果使触发容器的BFC，那么容器将会包裹着浮动元素。<br><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/web_img/197.png" alt=""></p>
<h4 id="3、BFC可以阻止元素被浮动元素覆盖"><a href="#3、BFC可以阻止元素被浮动元素覆盖" class="headerlink" title="3、BFC可以阻止元素被浮动元素覆盖"></a><strong>3、BFC可以阻止元素被浮动元素覆盖</strong></h4><p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/web_img/198.png" alt=""><br>这时候其实第二个元素有部分信息被浮动元素所覆盖，</p>
<p>如果想避免元素被覆盖，可触发第二个元素的BFC特性，在第二个元素中加入overflow：hidden，就会变成：<br><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/web_img/199.png" alt=""></p>
<p>这样就阻止了元素被浮动元素覆盖</p>
<p>最后希望大家对BFC有所了解，加油!</p>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/web_img/190.png?x-oss-process=image/resize,m_fill,h_180,w_250" alt=""></p>
<h2 id="参考文献："><a href="#参考文献：" class="headerlink" title="参考文献："></a>参考文献：</h2><p><a href="https://zhuanlan.zhihu.com/p/25321647" target="_blank" rel="noopener">https://zhuanlan.zhihu.com/p/25321647</a></p>

      
      <!-- reward -->
      
    </div>
      <!-- copyright -->
      
    <footer class="article-footer">
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/BFC/" rel="tag">BFC</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/CSS/" rel="tag">CSS</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%AE%9A%E4%BD%8D%E6%96%B9%E6%A1%88/" rel="tag">定位方案</a></li></ul>


    </footer>

  </div>

  
  
  <nav class="article-nav">
    
      <a href="/2020/02/20/%E7%BD%91%E7%BA%A2%E9%9D%A2%E8%AF%95%E9%A2%98/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            网红面试题[&#39;1&#39;,&#39;2&#39;,&#39;3&#39;].map(parseInt)
          
        </div>
      </a>
    
    
      <a href="/2020/02/18/%E9%9D%9E%E7%88%B6%E5%AD%90%E7%BB%84%E4%BB%B6%E9%97%B4%E7%9A%84%E4%BC%A0%E5%80%BC%E9%97%AE%E9%A2%98/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">非父子组件之间的传值</div>
      </a>
    
  </nav>


  

  
  
<!-- valine评论 -->
<div id="vcomments-box">
    <div id="vcomments">
    </div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src='https://cdn.jsdelivr.net/npm/valine@1.3.10/dist/Valine.min.js'></script>
<script>
    new Valine({
        el: '#vcomments',
        notify: false,
        verify: '',
        app_id: '',
        app_key: '',
        path: window.location.pathname,
        avatar: 'mp',
        placeholder: '给我的文章加点评论吧~',
        recordIP: true
    });
    const infoEle = document.querySelector('#vcomments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
        infoEle.childNodes.forEach(function (item) {
            item.parentNode.removeChild(item);
        });
    }
</script>
<style>
    #vcomments-box {
        padding: 5px 30px;
    }

    @media screen and (max-width: 800px) {
        #vcomments-box {
            padding: 5px 0px;
        }
    }

    #vcomments-box #vcomments {
        background-color: #fff;
    }

    .v .vlist .vcard .vh {
        padding-right: 20px;
    }

    .v .vlist .vcard {
        padding-left: 10px;
    }
</style>

  

  
  
  

</article>
</section>
      <footer class="footer">
  <div class="outer">
    <ul class="list-inline">
      <li>
        &copy;
        2020-2021
        张金
      </li>
      <li>
        
      </li>
    </ul>
    <ul class="list-inline">
      <li>
        
        
        <span>
  <i>PV:<span id="busuanzi_value_page_pv"></span></i>
  <i>UV:<span id="busuanzi_value_site_uv"></span></i>
</span>
        
      </li>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
        <img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/beian.png">
        <a href="https://beian.miit.gov.cn"  style="color:#f72b07" target="_blank">陕ICP备20002449号</a>
      </li>

    </ul>
  </div>
</footer>
    <div class="to_top">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>
      </div>
    </main>
      <aside class="sidebar">
        <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="Yolin"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/playlist">歌单</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/video">视频</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于我</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友情链接</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
      </aside>
      <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
      
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/jquery.justifiedGallery.min.js"></script>


<script src="/js/lazyload.min.js"></script>


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<script src="/js/share.js"></script>




<script>
  try {
    var typed = new Typed("#subtitle", {
    strings: ['肠断月明红豆蔻,','月似当时,','人似当时否？'],
    startDelay: 1500,
    typeSpeed: 200,
    loop: true,
    backSpeed: 40,
    showCursor: true
    });
  } catch (err) {
  }
  
</script>




<script src="/js/tocbot.min.js"></script>

<script>
  // Tocbot_v4.7.0  http://tscanlin.github.io/tocbot/
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer:'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto',
    onClick: (e) => {
      $('.toc-link').removeClass('is-active-link');
      $(`a[href=${e.target.hash}]`).addClass('is-active-link');
      $(e.target.hash).scrollIntoView();
      return false;
    }
  });
</script>


<script>
  var ayerConfig = {
    mathjax: true
  }
</script>


<script src="/js/ayer.js"></script>


<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>



<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
      tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
  });

  MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for(i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
      }
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@2.7.6/unpacked/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>


<script type="text/javascript" src="https://js.users.51.la/20544303.js"></script>
  </div>
</body>

</html>